<template>
	<view>
		<u-toast ref="uToast" />
		<common :tips='commonTips'></common>
		<u-modal v-model="modelShow" :mask-close-able="true" :show-cancel-button="true"
			:content="modelContent"></u-modal>
		<u-action-sheet :list="userStatusList" :safe-area-inset-bottom="true" v-model="userStatusBool"></u-action-sheet>
		<u-cell-group :border="false" class="user-info-box">
			<u-cell-item :arrow="false" title="单个金额">
				<view slot="right-icon">
					<u-input placeholder="0.00" :clearable="false" input-align="right" type="number"
						@input="onMoneyInput" v-model="redpacketdata.redpacket_money" :border="false" />
				</view>
			</u-cell-item>
			<u-cell-item hover-class="none" :border-bottom="false" :border-top="false" :arrow="false" title="">
				<!-- <view slot="right-icon"> -->
				<u-input placeholder="恭喜发财 大吉大利" :clearable="false" input-align="left" type="text"
					v-model="redpacketdata.meno" :border="false" />
				<!-- </view> -->
			</u-cell-item>
		</u-cell-group>
		<view class="im-data-none" v-if="type == 'group' && info.deletetime">群聊已解散~</view>
		<view class="user-buttons">
			<u-button @click="send" type="error">塞钱进红包</u-button>
		</view>
	</view>
</template>

<script>
	import Config from "@/common/config.js"; // 本地配置数据
	export default {
		data() {
			return {
				money: 0,
				id: 0,
				type: '',
				userStatusBool: false,
				userStatusList: [{
					text: '在线',
					color: '#21E589'
				}, {
					text: '忙碌',
					color: '#FF647E'
				}, {
					text: '隐身',
					color: '#FF9C4E'
				}],
				info: {
					status: {
						value: 0,
						chinese: '加载中'
					}
				},
				detail: [],
				buttons: [],
				userinfo: [],
				modelShow: false,
				modelContent: '',
				commonTips: '',
				collectionSelected: new Set(),
				redpacketdata: {
					meno: "恭喜发财，大吉大利",
					redpacket_money: "",
					to_user_id: "",
					redpacketdata: {
						is_group: false,
					}

				}
			}
		},
		onLoad: function(query) {
			this.id = query.id ? query.id : 0
			console.log(this.id);
			this.type = query.type ? query.type : 'user'
			this.userinfo = uni.getStorageSync('userinfo'); // 防止需要在pageDataLoad使用到用户ID
			let data = {
				im_tourists_token: this.userinfo.auth_token
			}
			this.$u.post('/api/Redpacket/userinfo',
				data).then(res => {
				this.money = res.data.money
			});
			this.ws.pageFun(this.pageDataLoad, this);
		},
		onShow() {
			this.ws.checkNetwork(this)
			if (this.ws.pageRefresh.centerInfo) {
				this.ws.pageRefresh.centerInfo = false
				this.ws.pageFun(this.pageDataLoad, this);
			}
		},
		onPullDownRefresh: function() {
			this.ws.pageFun(this.pageDataLoad(true), this);
			this.ws.onMessageCallBack.set('info-detail', (msg) => {
				if (msg.data.data.refresh) {
					this.$refs.uToast.show({
						title: '刷新成功~',
						type: 'success'
					})
					uni.stopPullDownRefresh()
				}
			})
		},
		methods: {
			onMoneyInput(val) {
				// 保留两位小数的数字
				let formatted = val.replace(/[^\d.]/g, '') // 只保留数字和小数点
					.replace(/^\./g, '') // 开头不能是点
					.replace(/\.{2,}/g, '.') // 不能出现连续两个点
					.replace('.', '#') // 暂时替换第一个点
					.replace(/\./g, '') // 移除其他点
					.replace('#', '.') // 替换回第一个点
					.replace(/^(\d+)\.(\d{0,2}).*$/, '$1.$2'); // 保留小数点后两位
				this.redpacketdata.redpacket_money = formatted;
			},
			send: async function() {
				let userinfo = uni.getStorageSync('userinfo');
				const moneyValue = parseFloat(this.redpacketdata.redpacket_money);
				if (isNaN(moneyValue) || moneyValue < 0.01) {
					this.$refs.uToast.show({
						title: '金额必须大于 0.01 元',
						type: 'error'
					});
					return;
				}
				if (Number(this.money) < Number(this.redpacketdata.redpacket_money)) {
					this.$refs.uToast.show({
						title: '余额不足~',
						type: 'success'
					});
					uni.redirectTo({
						url: '/pages/center/recharge_shande'
					});
					return;
				}
				let userToken = userinfo.token;
				// console.log(uni.getStorageSync("recipient_id"));
				// 构造 message 对象（这里也可以定义个变量 message）
				let redpacketdata = {
					...this.redpacketdata,
					is_group: false,
					is_used: 0,
					to_user_id: uni.getStorageSync("recipient_id"),
				};
				console.log(JSON.stringify(redpacketdata, null, 2))
				try {
					const res = await this.$u.post(`https://${Config.baseUrl}/api/Redpacket/createRedpacket?im_tourists_token=` + userToken,
						redpacketdata);
					console.log("发送红包响应", res);
					// 构造完整消息
					let message = {
						messageId: Date.now(), // 或者你自己的ID生成逻辑
						meno: redpacketdata.meno,
						redpacket_money: redpacketdata.redpacket_money,
						to_user_id: redpacketdata.to_user_id,
						redPackedId: res.data.id,
						is_used: 0,
						isGroup: false,
						from_user_id: userinfo.user_id,
						type: 'redpacketdata'
					};
					// 发送给上层页面（如消息列表页）
					uni.$emit('redpacketdata', {
						message
					});
					// 返回上一页
					uni.navigateBack({
						delta: 1
					});
				} catch (error) {
					console.error("发送红包失败", error);
					this.$refs.uToast.show({
						title: '发送失败，请重试',
						type: 'error'
					});
				}
			}

		}
	}
</script>

<style lang="scss">
	page {
		background-color: $--bg-color;
	}

	.user-box {
		display: flex;
		padding: 20rpx 4vw;
		align-items: center;
	}

	.user-avatar {
		height: 170rpx;
		width: 170rpx;
	}

	.collection-user {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.user-right {
		width: 70%;
		padding-left: 20rpx;
	}

	.user-right-item {
		display: block;
		line-height: 32rpx;
	}

	.user-name {
		line-height: 46rpx;
		font-size: 30rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.nickname-text {
		display: inline-flex;
		max-width: 46%;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.user-status {
		color: $--gray;
		line-height: 46rpx;
	}

	.user-info-box {
		display: block;
		width: 92vw;
		margin: 0 auto;
		padding-top: 10rpx;
	}

	.user-buttons {
		padding: 40rpx 0;
		display: flex;
		align-items: center;
		justify-content: space-around;
	}

	.leader-avatar-box {
		display: flex;
		align-items: center;
	}

	.leader-avatar {
		height: 80rpx;
		width: 80rpx;
		margin-right: 10rpx;
	}

	.im-data-none {
		display: block;
		line-height: 100rpx;
		text-align: center;
		font-size: 28rpx;
		color: $--gray;
	}
</style>